package com.ylr.自定义枚举类校验;


import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;

@Target({ElementType.METHOD,ElementType.FIELD,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValueValidatorTest.Validator.class)//指定实现类
public @interface EnumValueValidatorTest {
    String message() default "{EnumValueValidator's value is invalid}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 允许的枚举
     * @return
     */
    Class<? extends Enum<?>> enumClass();

    boolean isList() default false;

    /**
     * 校验调用的枚举类的方法
     * @return
     */
    String method();

    class Validator implements ConstraintValidator<EnumValueValidatorTest, Object> {

        private Class<? extends Enum>  enumClass ;
        private Boolean isList = false;
        private String methodStr;

        @Override
        public void initialize(EnumValueValidatorTest constraintAnnotation) {
            enumClass  = constraintAnnotation.enumClass();
            isList = constraintAnnotation.isList();
            methodStr = constraintAnnotation.method();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if (value == null) return  false;
            if (isList){
                boolean instance = value instanceof List;
                if (!instance) return false;



                return instance;
            }else {
                    // 获取所有的枚举值
                    Enum[] enums = enumClass.getEnumConstants();
                    // 对每一个枚举值调用 校验的方法，获取返回值，和入参作比较
                    for (Enum e : enums) {
                        if (e.name().equalsIgnoreCase(value.toString())) {
                            System.out.println(e.name().equalsIgnoreCase(value.toString()));
                            return true;
                        }
                    }
                    return false;
            }

        }

    }
}
